package com.example.idlefish.MyAccount.activity


import android.annotation.*
import android.os.*
import android.util.Log
import android.view.*
import android.widget.*
import androidx.appcompat.app.*
import androidx.recyclerview.widget.*
import com.example.idlefish.*
import com.example.idlefish.MyAccount.contract.HomepageContract
import com.example.idlefish.MyAccount.pojo.*
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.CommonUtil
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.PublicModule.UserConst.Companion.id
import com.example.idlefish.databinding.*
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.*

class MeFollowActivity  : AppCompatActivity()  {
    private lateinit var binding: MyaccountFollowBinding
    private var index = -1
    private var position = -1
    private val client = OkHttpClient()
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()
    private val mapper = ObjectMapper()
    private var userFollowList = ArrayList<UserInList>()
    private var adapter = UserFollowAdapter(userFollowList)


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = MyaccountFollowBinding.inflate(layoutInflater)
        setContentView(binding.root)


        // val id = CommonUtil.getSerializable(intent, "id", Long::class.java)
        val id = intent.getLongExtra("id", -1)
        Log.i("日志MeFollowActivity接受信息", "id: $id")

        binding.loading.show()

        // 列表
        initList(id)

        setSupportActionBar(binding.toolbar)

        val layoutManager = LinearLayoutManager(this)
        binding.userFollowList.layoutManager = layoutManager
        binding.userFollowList.adapter = adapter

    }

    private fun initList(id: Long) {
        try {
            val request = Request.Builder()
                .url(NetworkSettings.USER + "queryFollowToList?id=${id}")
                .get().build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val gson = Gson()
                    val responseData = response.body?.string()
                    val data = gson.fromJson(responseData, UserInListResult::class.java)
                    val info = data.data

                    handler.post {
                        userFollowList.addAll(info)
                        binding.loading.hide()
                        adapter.notifyDataSetChanged()
                        Log.i("关注列表", "$userFollowList")
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
    }

    private val homepageLauncher = registerForActivityResult(HomepageContract()) { result ->

    }

    private inner class UserFollowAdapter(private val userToList: ArrayList<UserInList>) :
        RecyclerView.Adapter<UserFollowAdapter.ViewHolder>() {
        // 创建ViewHolder实例，我们在这个方法中将elem布局加载进来，
        // 创建一个ViewHolder实例，并把加载出来的布局传入构造函数当中，最后将ViewHolder的实例返回。
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.myaccount_follow_elem, parent, false)
            val viewHolder = ViewHolder(view)

            // 单击元素
            viewHolder.itemView.setOnClickListener {
                val position = viewHolder.absoluteAdapterPosition
                val info = userToList[position]
                index = position

                // Toast.makeText(parent.context, "点击了${info.nickname}", Toast.LENGTH_SHORT).show()
                homepageLauncher.launch(info.id)
            }

            // 删除
/*            viewHolder.deleteButton.setOnClickListener {
                position = viewHolder.absoluteAdapterPosition
                delete(userFansList[position].trainId!!)
                userFansList.removeAt(position)
                notifyItemRemoved(position)
            }*/
            return viewHolder
        }

        // RecyclerView 子项的最外层布局
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val avatar: ImageView = view.findViewById(R.id.follow_avatar)
            val nickname: TextView = view.findViewById(R.id.follow_nickname)
            val intro: TextView = view.findViewById(R.id.follow_introduction)
            val fansNum : TextView = view.findViewById(R.id.follow_fansNum)

  /*    val deleteButton: Button = view.findViewById(R.id.button_delete)*/
        }

        // 对 RecyclerView 子项的数据进行赋值，会在每个子项被滚动到屏幕内的时候执行
        // 通过 position参数得到当前项的info实例，然后再将数据设置到ViewHolder的TextView当中即可
        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val info = userToList[position]
            holder.avatar.setImageBitmap(info.avatar?.let {
                ApplicationConst.decodeBase64ToImage(applicationContext,
                    it
                )
            })
            holder.nickname.text = info.nickname
            holder.intro.text = info.intro
            holder.fansNum.text = "${info.fansNum}"




        }

        override fun getItemCount() = userToList.size

    }



    fun back() {
        finish()
    }

    fun back(view: View) {
        finish()
    }

}